package com.example.gamestore.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.gamestore.Bean.Cart;
import com.example.gamestore.Bean.CartItem;
import com.example.gamestore.Bean.OrderItem;
import com.example.gamestore.Bean.Orders;
import com.example.gamestore.mapper.AddressMapper;
import com.example.gamestore.mapper.OrderItemMapper;
import com.example.gamestore.mapper.OrderMapper;
import com.example.gamestore.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Service
public class OrderServiceImp implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Override
    public String createOrder(Cart cart, Integer userId) {
        String orderid=System.currentTimeMillis()+""+userId;
        Orders orders=new Orders(orderid,new Date(),cart.getTotalPrice(),0,userId);
        orderMapper.insert(orders);
        Set<Map.Entry<Integer, CartItem>> entries = cart.getItems().entrySet();
        for (Map.Entry<Integer, CartItem> entry : entries) {
            CartItem cartItem = entry.getValue();
            OrderItem orderItem=new OrderItem(null,cartItem.getName(),cartItem.getCount(),cartItem.getPrice(),cartItem.getTotalPrice(),orderid);
            orderItemMapper.insert(orderItem);
        }
        cart.clear();
        return orderid;
    }

    @Override
    public List<Orders> selectOrdersById(Integer id) {
        LambdaQueryWrapper<Orders> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId,id).orderByDesc(Orders::getCreateTime);
        List<Orders> ordersList = orderMapper.selectList(wrapper);
        return ordersList;
    }

    @Override
    public Orders selectOrderByID(String orderId) {
        LambdaQueryWrapper<Orders> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getOrderId,orderId);
        return orderMapper.selectOne(wrapper);
    }

    @Override
    public void deleteOrderById(String orderId) {
        LambdaQueryWrapper<OrderItem> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(OrderItem::getOrderId,orderId);
        orderItemMapper.delete(wrapper);
        addressMapper.deleteById(orderId);
        orderMapper.deleteById(orderId);
    }
}
